class Ticket < ApplicationRecord
  def self.get_ticket(source, app_id, app_secret)

    ticket = Ticket.find_by(source: source)
    if ticket
      if (Time.now - ticket.updated_at).to_i > 7100
        ticket.update_attribute(:jsapi_ticket, get_jsapi_ticket_from_weixin(source,app_id, app_secret) )
      end
    else
      ticket = Ticket.create!(source: source, jsapi_ticket: get_jsapi_ticket_from_weixin(source,app_id, app_secret))
    end
    ticket.jsapi_ticket
  end

  def self.get_jsapi_ticket_from_weixin(source,app_id, app_secret)

    access_token = WeixinAccesstoken.get_token(source, app_id, app_secret)

    uri = URI("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=#{access_token}&type=jsapi")
    respond = Net::HTTP.get_response(uri)
    if ticket = ActiveSupport::JSON.decode(respond.body)['ticket']
      ticket
    else
      raise
    end
  end
end
